<template>
	<van-sticky>
	<van-search readonly v-model="orderCondition.key" placeholder="搜索我的订单" shape="round" background="var(--body-bg-color)"
				show-action @click-input="showCondition=true">
		<template #left><van-icon name="arrow-left" class="btn-back van-haptics-feedback" @click="goBack"/></template>
		<template #action>
			<van-icon name="weapp-nav" class="btn-more van-haptics-feedback"/>
		</template>
	</van-search>
	<van-tabs v-model:active="orderCondition.ordStatus" @change="handleTabChange">
		<template #nav-right>
			<van-dropdown-menu class="nav-right">
				<van-dropdown-item ref="itemRef" @open="showDropdown">
					<template #title>
						<van-icon name="arrow-down"/>
					</template>
					<div class="cell-group">
						<div class="cell-title">订单状态</div>
						<ul class="item-list">
							<li :class="sts.value===tmpVal.ordStatus? 'active':0" v-for="sts in ordSts" @click="selectTmpSts(sts.value)">{{sts.text}}</li>
						</ul>
					</div>
					<div class="popup-btn"><van-button block round type="primary" @click="handleTabChange(tmpVal.ordStatus)">确 定</van-button></div>
				</van-dropdown-item>
			</van-dropdown-menu>
		</template>
		<van-tab v-for="sts in ordSts" :title="sts.text" :name="sts.value" :key="sts.value"/>
	</van-tabs>
	</van-sticky>
	<van-popup v-model:show="showCondition" teleport="#app" position="bottom" class="drawer-bottom" round closeable @closed="handlePopupClose">
		<div class="popup-title">搜索条件</div>
		<div class="main-wrap">
			<van-field v-model="tmpVal.key" label="关键字" placeholder="请输入货品名称或订单号" :formatter="(val:string)=>val.trim()" />
			<van-field v-model="tmpVal.linker" label="收货人姓名" placeholder="请输入收货人姓名" :formatter="(val:string)=>val.trim()" />
			<van-field v-model="tmpVal.linkPhone" label="收货人号码" type="tel" placeholder="请输入收货人联系电话" :formatter="(val:string)=>val.trim()" />
			<div class="cell-group">
				<div class="cell-title">订单金额(元)</div>
				<div class="cell-wrap">
					<van-stepper v-model="tmpVal.minMoney" integer :min="0" :max="999999999" :show-plus="false" default-value="" placeholder="￥最低金额"
								 :show-minus="false" :long-press="false" :allow-empty="true"/> -
					<van-stepper v-model="tmpVal.maxMoney" integer :min="tmpVal.minMoney" :max="999999999" :show-plus="false" default-value="" placeholder="￥最高金额"
								 :show-minus="false" :long-press="false" :allow-empty="true"/>
				</div>
			</div>
			<div class="cell-group">
				<div class="cell-title">时间范围</div>
				<div class="cell-wrap">
					<div class="item-list">
						<li v-for="t in timeTypeMap" :key="t.value" @click="selectTimeType(t.value)" :class="t.value===tmpVal.timeType? 'active':''">{{t.text}}</li>
					</div>
					<van-cell @click="showCalendar=true" style="margin-bottom:-10px;" icon="calendar-o" v-show="tmpVal.timeType==='3'" is-link :value="timeRangeText"></van-cell>
				</div>
			</div>
			<div class="cell-group">
				<div class="cell-title">来源类型</div>
				<div class="cell-wrap">
					<ul class="item-list">
						<li v-for="sts in orderFrom" :key="sts.value" @click="selectOrdFrom(sts.value)" :class="sts.value===tmpVal.ordFrom? 'active':''">{{sts.text}}</li>
					</ul>
				</div>
			</div>
		</div>
		<div class="drawer-btn">
			<van-button type="warning" block class="button-first" @click="resetCondition()">重置</van-button>
			<van-button type="primary" block class="button-last"  @click="handleQuery">搜索</van-button>
		</div>
	</van-popup>
	<van-calendar v-model:show="showCalendar" :allow-same-day="true" :default-date="[beginDate,endDate]" type="range" @confirm="onCaleConfirm" :max-date="maxDate" :min-date="minDate"/>
</template>
<style lang="scss" scoped>
.van-search{
	--van-search-content-background:#dfdfdf;
	//--van-search-padding:8px var(--van-padding-sm);
	:deep(.van-field__control::placeholder){color:var(--font-third-color);}
	.btn-back{
		height:34px;font-size:18px;line-height:34px; width:34px; text-align: center; border-radius:18px; background:var(--white-color);
		margin-right:10px;
	}
	.btn-more{
		height:32px;padding:0 5px;font-size:18px;line-height:32px;
	}
}
.van-tabs{
	margin-top:-8px;z-index:1;
	--van-tabs-nav-background:var(--body-bg-color);
	--van-tabs-bottom-bar-width:60px;
	:deep(.van-tab--active){font-size:16px;}
	:deep(.van-tabs__nav--line.van-tabs__nav--complete){padding-right:0;}
	.nav-right{
		position:sticky;display:block; width:42px;height:44px; right:0;top:0; background:var(--body-bg-color); text-align:center; line-height: 44px;
		.van-icon{width:42px;font-size:18px;}
		:deep(.van-dropdown-menu__bar){
			height:44px; background: transparent; box-shadow:none;
		}
		:deep(.van-dropdown-menu__title){
			padding:0;
			&::after{display:none;}
		}
	}
	.popup-btn{
		padding:8px 16px; height:50px;
		.van-button{height:36px;}
	}
	.cell-group{
		position:relative;
		padding: 0 14px;
		line-height: 1.2;
		&::after{
			position: absolute;
			box-sizing: border-box;
			content: " ";
			pointer-events: none;
			right: var(--van-padding-md);
			bottom: 0;
			left: var(--van-padding-md);
			border-bottom: 1px solid var(--van-cell-border-color);
			transform: scaleY(.5);
		}
		.cell-title{
			color:var(--font-third-color);padding:10px 2px;font-size:14px;
			display:flex;align-items: center;
		}
		:deep(.van-stepper__input){
			border-radius:16px; width:42vw; height:32px;
			&::placeholder{color:var(--font-disable-color);}
		}
		.item-list{
			margin:0 -10px 10px 0;display:flex;padding:0; flex-wrap:wrap; overflow:hidden;
			&>li{
				display:block; text-align:center; line-height:30px; width:calc((100vw - 48px)/3);
				//max-width:calc(50vw - 20px);
				overflow: hidden; white-space: nowrap; text-overflow: ellipsis; position:relative; color:var(--font-second-color);
				margin:0 10px 10px 0;padding:0 10px;height:32px;border-radius:20px; font-size:13px;
				border:1px solid var(--bar-input-color);

				&::before{
					width:100%;height:100%; top:0;left:0;position:absolute;content:" ";
					background-color:var(--bar-input-color);z-index:-1;
				}
				&.active{
					border-color:var(--van-primary-color);color:var(--van-primary-color);
					&::before{
						background-color:var(--van-primary-color); opacity: .1;
					}
				}
				//&.more-items{
				//	border-color:var(--border-color);
				//}
			}
			&.shop-item>li{
				width:calc(50vw - 21px);
			}
		}
	}
}
.popup-title{height:48px;display:flex;align-items:center; justify-content: center}
.main-wrap {
	height: calc(84vh - 98px);
	.cell-group{
		position:relative;
		&::after{
			position: absolute;
			box-sizing: border-box;
			content: " ";
			pointer-events: none;
			right: var(--van-padding-md);
			bottom: 0;
			left: var(--van-padding-md);
			border-bottom: 1px solid var(--van-cell-border-color);
			transform: scaleY(.5);
		}
		.cell-title{
			color:var(--font-first-color);padding:10px 16px;font-size: 15px;
			display:flex;align-items: center;justify-content:space-between;
			.right-info{color:var(--font-third-color);font-size:12px;}
		}
		.cell-wrap{
			padding:0 16px 10px 16px;
		}
		:deep(.van-stepper__input){
			border-radius:16px; width:42vw; height:32px;
			&::placeholder{color:var(--font-disable-color);}
		}
		.item-list{
			margin:0 -10px -10px 0;display:flex;padding:0; flex-wrap:wrap; overflow:hidden;
			&>li{
				display:block; text-align:center; line-height:30px; width:calc((100vw - 52px)/3);
				//max-width:calc(50vw - 20px);
				overflow: hidden; white-space: nowrap; text-overflow: ellipsis; position:relative; color:var(--font-second-color);
				margin:0 10px 10px 0;padding:0 10px;height:32px;border-radius:20px; font-size:13px;
				border:1px solid var(--bar-input-color);

				&::before{
					width:100%;height:100%; top:0;left:0;position:absolute;content:" ";
					background-color:var(--bar-input-color);z-index:-1;
				}
				&.active{
					border-color:var(--van-primary-color);color:var(--van-primary-color);
					&::before{
						background-color:var(--van-primary-color); opacity: .1;
					}
				}
				&.more-items{
					border-color:var(--border-color);
				}
			}
			&.time-item>li{
				width:calc(50vw - 21px);
			}
		}
	}
}
</style>
<script lang="ts" setup>
import _ from "lodash";
import {SearchOrderCondition} from "@/types";
const route=useRoute()
const {goBack,to,replace} = useGoto()
const {ordStatusMap,orderFromMap} = useKV()

const emits=defineEmits(['onSearch'])

//data
let firstQuery=true
//订单查询的搜索条件：当查询条件确定改变时，触发改变事件，以使父组件进行重新查询
const {orderCondition} =useSearch()
//显示选项时临时展示用的搜索条件
const tmpVal =reactive<SearchOrderCondition>({
	ordStatus:orderCondition.ordStatus,  //订单状态
	key:orderCondition.key,		//查询关键字 （货品名称/订单号）
	linker:'',					//联系人姓名
	linkPhone:'',				//联系人电话
	ordFrom:'',                 //来源类型 ‘’:不限 0:本平台 1:撮合系统 2:优品小店  3:京东
	maxMoney:'',                 //订单金额最大值(元)
	minMoney:'',                 //订单金额最小值(元)
	timeType:'1',               //查询时间段类型： ‘3’：自定义  ‘1’：3月内   ‘2’：3月前
	dateRange:null,
})
const itemRef = ref(null)
const ordSts=ref(<Array<any>>[{text:'全部',value:'00'}])
let tmpStsList=<any>[]
for(let k in ordStatusMap){
	if(k.indexOf('0')===0)	ordSts.value.push({text:ordStatusMap[k as keyof typeof ordStatusMap], value:k})
	else	tmpStsList.push({text:ordStatusMap[k as keyof typeof ordStatusMap], value:k})
}
for(let item of tmpStsList){
	ordSts.value.push(item)
}
const orderFrom = ref(<Array<any>>[{text:'不限',value:''}])
for(let k in orderFromMap){
	orderFrom.value.push({text:orderFromMap[k as keyof typeof orderFromMap], value:k})
}
const timeTypeMap=ref([
	{text:'3个月内',value:'1'}, {text:'3个月前',value:'2'}, {text:'自定义',value:'3'}
])
const showCondition=ref(false)
const showCalendar=ref(false)
let now = new Date()
let last6Month =new Date(now.getTime()-86400000*180)
let minDate = new Date(now.getFullYear()-5, 0, 1)
let maxDate = new Date(now.getFullYear(),now.getMonth(),now.getDate())
let beginDate = last6Month, endDate = now

//computed
const timeRangeText=computed(()=>{
	if(tmpVal.timeType!=='3')	return ''
	else{
		if(!tmpVal.dateRange || tmpVal.dateRange.length!==2) {
			return '请选择开始/结束时间点'
		}else{
			return tmpVal.dateRange[0]+' ~ '+tmpVal.dateRange[1]
		}
	}
})

//methods
//从get传参中获取查询条件
const getParamFromUrl=()=>{
	if(route.query.ordStatus)	orderCondition.ordStatus = route.query.ordStatus as string
	else	orderCondition.ordStatus='00'
	if(route.query.key)	orderCondition.key = route.query.key as string
	else	orderCondition.key=''
	if(route.query.linker)	orderCondition.linker = route.query.linker as string
	else	orderCondition.linker=''
	if(route.query.linkPhone)	orderCondition.linkPhone = route.query.linkPhone as string
	else	orderCondition.linkPhone=''
	if(route.query.ordFrom)	orderCondition.ordFrom = route.query.ordFrom as string
	else	orderCondition.ordFrom=''
	if(route.query.minMoney)	orderCondition.minMoney = route.query.minMoney as string
	else	orderCondition.minMoney=''
	if(route.query.maxMoney)	orderCondition.maxMoney = route.query.maxMoney as string
	else	orderCondition.maxMoney=''
	if(route.query.timeType)	orderCondition.timeType = route.query.timeType as string
	else	orderCondition.timeType='1'
	if(orderCondition.timeType==='3'){
		if(route.query.dateRange){
			orderCondition.dateRange = route.query.dateRange as string
		}
	}else {
		delete orderCondition.dateRange
	}
	resetCondition(orderCondition)
}
//组装并返回纯粹的查询条件JSON
const buildJsonData=(cond:SearchOrderCondition)=>{
	let query = JSON.parse(JSON.stringify(cond))
	for(let k in query){
		if(!query[k]||query[k]==='')	delete query[k]
	}
	if(query.ordStatus==='00')	delete query['ordStatus']
	if(query.timeType!=='3'){
		delete query['dateRange']
	}
	return query
}

const selectTmpSts=(val:string)=>{
	tmpVal.ordStatus=val
}
const selectOrdFrom=(val:string)=>{
	tmpVal.ordFrom=val
}
const selectTimeType=(val:string)=>{
	tmpVal.timeType=val
	if(val!=='3'){
		delete tmpVal.dateRange
	}
}

const onCaleConfirm=(date:any)=>{
	showCalendar.value = false
	let [start, end] = date;
	tmpVal.dateRange=[]
	let month=start.getMonth()+1, day=start.getDate();
	tmpVal.dateRange[0] = start.getFullYear()+'-'+_.padStart(month, 2, '0')+'-'+_.padStart(day, 2, '0')
	month=end.getMonth()+1; day=end.getDate();
	tmpVal.dateRange[1] = end.getFullYear()+'-'+_.padStart(month, 2, '0')+'-'+_.padStart(day, 2, '0')
}

const showDropdown=()=>{
	tmpVal.ordStatus = orderCondition.ordStatus
	itemRef.value.toggle(true)
}

const resetCondition=(cond?:any)=>{
	if(cond){
		tmpVal.ordStatus = cond.ordStatus  //订单状态
		tmpVal.key = cond.key				 //查询关键字 （货品名称/订单号）
		tmpVal.linker = cond.linker		 //联系人姓名
		tmpVal.linkPhone = cond.linkPhone	 //联系人电话
		tmpVal.ordFrom = cond.ordFrom      //来源类型 ‘’:不限 0:本平台 1:撮合系统 2:优品小店  3:京东
		tmpVal.maxMoney = cond.maxMoney    //订单金额最大值(元)
		tmpVal.minMoney = cond.minMoney    //订单金额最小值(元)
		tmpVal.timeType = cond.timeType    //查询时间段类型： ‘’：自定义  ‘1’：3月内   ‘2’：3月前
		tmpVal.dateRange = cond.dateRange  //查询时间段
	}else{
		tmpVal.ordStatus = '00'
		tmpVal.key = ''
		tmpVal.linker = ''
		tmpVal.linkPhone = ''
		tmpVal.ordFrom = ''
		tmpVal.maxMoney = ''
		tmpVal.minMoney = ''
		tmpVal.timeType = '1'
		tmpVal.dateRange = null
	}
}

const handlePopupClose=()=>{
	itemRef.value.toggle(false)
	resetCondition(orderCondition)
}

const handleTabChange=(val:string)=>{
	itemRef.value.toggle(false)
	tmpVal.ordStatus=val
	replace('/order/myOrders',buildJsonData(tmpVal))

}
const handleQuery=()=>{
	itemRef.value.toggle(false)

	showCondition.value=false
	if(firstQuery){
		firstQuery=false
		to('/order/myOrders',buildJsonData(tmpVal))
	}else{
		replace('/order/myOrders',buildJsonData(tmpVal))
	}
}

//动态监视路由fullPath，实时更改查询条件并触发查询
watch(
	()=>route.fullPath,
	(newVal)=>{
		console.log('fullpath',newVal)
		getParamFromUrl()
		emits('onSearch',buildJsonData(orderCondition))
	},{immediate:true}
)

//onMounted(()=>{console.log('OrderQueryBar mounted')})

defineExpose({

})
</script>